package com.hexinfo.dmpro.admin.controller;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.hexinfo.dmpro.common.annotation.AnonymousAccess;
import com.hexinfo.dmpro.common.annotation.Log;
import com.hexinfo.dmpro.common.base.Page;
import com.hexinfo.dmpro.common.exception.BadRequestException;
import com.hexinfo.dmpro.admin.model.User;
import com.hexinfo.dmpro.admin.model.req.UserRequest;
import com.hexinfo.dmpro.admin.model.vo.UserPassVo;
import com.hexinfo.dmpro.admin.model.vo.UserVo;
import com.hexinfo.dmpro.admin.service.UserService;
import com.hexinfo.dmpro.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Set;

/**
 * @ClassName UserController
 * @Describe
 * @Author ml.wang
 * @Date 2021-06-18
 */
@Api(tags = "系统：用户管理")
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Value("${rsa.private_key}")
    private String privateKey;

    @Value("${resetPwd}")
    private String resetPwd;

    private final PasswordEncoder passwordEncoder;

    private final UserService userService;

    UserController(UserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @Log("查询用户")
    @ApiOperation("查询用户")
    @GetMapping
    @AnonymousAccess
//    @PreAuthorize("@permission.check('user:list')")
    public ResponseEntity<Object> queryAll(UserVo userView, Page page) {
       return new ResponseEntity<>(userService.queryAll(UserRequest.viewToRequest(userView), page), HttpStatus.OK);
    }

    @ApiOperation("通过userId查询RoleId")
    @GetMapping("/userId/{id}")
    @AnonymousAccess
    //通过userid查roleid
    public ResponseEntity<Object> selectByUserId(@PathVariable("id") Long id){
        return new ResponseEntity<>(userService.selectByUserId(id),HttpStatus.OK);
    }


    @ApiOperation("查询所有项目管理员")
    @GetMapping("/selectAllProjectManager")
    public ResponseEntity<Object> selectAllProjectManager() {
        return new ResponseEntity<>(userService.selectAllProjectManager(), HttpStatus.OK);
    }

    @ApiOperation("查询项目开发人员")
    @GetMapping("/selectAllProjectDeveloper")
    public ResponseEntity<Object> selectAllProjectDeveloper() {
        return new ResponseEntity<>(userService.selectAllProjectDeveloper(), HttpStatus.OK);
    }

    @Log("新增用户")
    @ApiOperation("新增用户")
    @PostMapping
    @PreAuthorize("@permission.check('user:add','platformManager', 'projectManager')")
    public ResponseEntity<Object> create(@Validated @RequestBody User resources) {
        userService.checkLevel(resources);
        // 默认密码 123456
        resources.setPassword(passwordEncoder.encode("123456"));
        userService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("修改用户")
    @ApiOperation("修改用户")
    @PutMapping
    @PreAuthorize("@permission.check('user:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody User resource) {
        userService.checkLevel(resource);
        userService.update(resource);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除用户")
    @ApiOperation("删除用户")
    @DeleteMapping
    @PreAuthorize("@permission.check('user:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) {
        User user = userService.findByName(SecurityUtils.getUsername());
        userService.checkLevel(user, ids);
        userService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("修改用户：个人中心")
    @ApiOperation("修改用户：个人中心")
    @PutMapping(value = "/center")
    public ResponseEntity<Object> center(@Validated @RequestBody User resource) {
        userService.updateCenter(resource);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @ApiOperation("修改密码")
    @PostMapping(value = "/updatePass")
    public ResponseEntity<Object> updatePass(@RequestBody UserPassVo passVo) {
        // 密码解密
        RSA rsa = new RSA(privateKey, null);
        String oldPass = new String(rsa.decrypt(passVo.getOldPass(), KeyType.PrivateKey));
        String newPass = new String(rsa.decrypt(passVo.getNewPass(), KeyType.PrivateKey));
        User user = userService.findByName(SecurityUtils.getUsername());
        if (!passwordEncoder.matches(oldPass, user.getPassword())) {
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if (passwordEncoder.matches(newPass, user.getPassword())) {
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        userService.modifyPassword(user.getId(), passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("重置密码")
    @PostMapping("/resetPass")
    public ResponseEntity<Object> resetPass(@RequestBody User user) {
        userService.modifyPassword(user.getId(), passwordEncoder.encode(resetPwd));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改头像")
    @PostMapping(value = "/updateAvatar")
    public ResponseEntity<Object> updateAvatar(@RequestParam MultipartFile file) {
        userService.updateAvatar(file);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("检验用户名重复")
    @PostMapping(value = "/verityUsername")
    public ResponseEntity<Object> verityUsername(@RequestBody String username) {
        return new ResponseEntity<>(userService.existUsername(username), HttpStatus.OK);
    }

}
